package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.security.MessageDigest

/**
 *
 * @Title: apiTpTdxGetEventCallBack*
 * @Description:泰迪熊话单数据回写
 * @remak ：提供给浙江泰迪熊系统话单数据回写
 * @author: TH*
 * @date 2023-10-16 11:11:00
 *
 */
public  class apiTpTdxGetEventCallBack implements ServiceBackInvoke  {

    private static final Log log = LogFactory.getLog(apiTpTdxGetEventCallBack.class);

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //初始化返回参数
        JSONObject result =new JSONObject();

        long starttime=System.currentTimeMillis();

        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        //获取接口调用方式及参数
        String GetMethod=httpServletRequest.getMethod();

        log.debug("[GetMethod]:"+GetMethod);


        String inData="";
        if (GetMethod.equals("GET")){
            inData=httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]"+inData);
        }else {
            InputStreamReader reader=new InputStreamReader(httpServletRequest.getInputStream(),"UTF-8");
            BufferedReader iny=new BufferedReader(reader);
            String line;
            while ((line=iny.readLine())!=null){
                inData+=line;
            }

            log.debug("[原始Post请求参数：]"+inData);
        }
        log.debug("[调用请求信息：]"+inData)


        if (KHUtil.isNull(inData)){
            log.error("入参为空-无法完成操作！");
            result.put("code",-2);
            result.put("message","入参为空-无法完成操作！");

            return  result.toString();
        }



        try {

            JSONObject inJson = JSONObject.fromObject(inData);
            String OBJECTIVE_GUID = null;
            String timestamp = GetJV(inJson, "timestamp");//时间戳
            String token = GetJV(inJson, "token");//token
            String callLog=GetJV(inJson, "callLog");//里层json

            JSONObject callLogJson = JSONObject.fromObject(callLog);
            def callid = GetJV(callLogJson, "callId");//呼叫ID
            def callType = GetJV(callLogJson, "callType");//呼叫类型
            def agentCode = GetJV(callLogJson, "agentCode");//坐席工号
            def agentName = GetJV(callLogJson, "agentName");//坐席名称
            def caller = GetJV(callLogJson, "caller");//主叫
            def called = GetJV(callLogJson, "called");//被叫
            def accessNumber = GetJV(callLogJson, "accessNumber");//接入号
            def alertingTime = GetJV(callLogJson, "alertingTime");//振铃时间
            def pickTime = GetJV(callLogJson, "alertingTime");//摘机时间
            def callInTime=GetJV(callLogJson, "callInTime");//呼叫时间
            def callEndTime = GetJV(callLogJson, "callEndTime");//结束时间
            def queueDuration = GetJV(callLogJson, "queueDuration");//等待时长
            def alertingDuration = GetJV(callLogJson, "alertingDuration");//振铃时长
            def agentDuration= GetJV(callLogJson, "agentDuration");//通话时长
            def status= GetJV(callLogJson, "status");//结束原因
            def recordFile= GetJV(callLogJson, "recordFile");//录音文件名称
            def province= GetJV(callLogJson, "province");//所属省份
            def city= GetJV(callLogJson, "city");//所属城市
            String ivrInputInfo = GetJV(callLogJson, "ivrInputInfo");//IVR输入内容
            String exendFieds=GetJV(callLogJson,"extendFields");
            if (!KHUtil.isNull(exendFieds)) {
                JSONObject  exendFiedsJson=JSONObject.fromObject(exendFieds);
                OBJECTIVE_GUID=GetJV(exendFiedsJson,"EXTEND1");//任务名单ID
            }

            String IsNullMSG =
                            KHUtil.isNullMSG("callLog",callLog)+
                            KHUtil.isNullMSG("callId", callid) +
                            KHUtil.isNullMSG("timestamp", timestamp) +
                            KHUtil.isNullMSG("token", token)+
                            KHUtil.isNullMSG("extendFields",exendFieds)+
                            KHUtil.isNullMSG("EXTEND1",OBJECTIVE_GUID)+
                            KHUtil.isNullMSG("caller", caller)+
                            KHUtil.isNullMSG("called", called)+
                            KHUtil.isNullMSG("status", status)+
                            KHUtil.isNullMSG("callEndTime", callEndTime)+
                            KHUtil.isNullMSG("callInTime", callInTime);
            if (!KHUtil.isNull(IsNullMSG)) {
                log.error("参数为必填项-无法完成操作！");
                result.put("result", -2);
                result.put("message", IsNullMSG + "参数为空-无法完成操作！");
                return result.toString();
            }
            /**
             * MD5(accessKey+timestamp+orgName)
             * accessKey是双方协商的参数
             */
            String accessKey = KHDBConfig.getParam(eliteBean, "TDKEY", "");//获取accessKey
            String orgName = KHDBConfig.getParam(eliteBean, "TDXQID", "");//orgName	企业id
            String isString = MD5(accessKey.toString() + timestamp.toString() + orgName.toString());//加个密看看
            log.debug("预期加密Token:" + isString);
            //校验通过
            if (token.equals(isString)) {
                log.debug("Token校验通过！");
            } else {
                log.error("Token校验不通过！");
                result.put("result", -2);
                result.put("message", "Token校验不通过-无法完成操作！");
                return result.toString();
            }

            String cxsql=''' 
                                  Select callId from  TDX_BILL_LIST tdx where 1=1
                                   and tdx.callId=?
                                   AND ROWNUM<=1
                                  ''';
            List<Map<String, Object>> cxselect  = jt.queryForList(cxsql,callid);

          if (cxselect.size()<=0){
              log.debug("收到【泰迪熊】话单表新增数据："+callid);
            String InsertSql='''   
                              Insert  into TDX_BILL_LIST
                              (REC_GUID,
                              OBJECTIVE_GUID,
                              callid,
                              callType,
                              agentCode,
                              agentName,
                              caller,
                              called,
                              accessNumber,
                              alertingTime,
                              pickTime,
                              callInTime,
                              callEndTime,
                              queueDuration,
                              alertingDuration,
                              agentDuration,
                              recordFile,
                              province,
                              city,
                              ivrInputInfo,
                              STATUS,
                              CREATEDDATE
                              ) Values(
                              sysguid,
                              ?,
                              ?,
                              ?,
                              ?,
                              ?,
                              ?, 
                              ?, 
                              ?,
                              ?,
                              ?, 
                              ?,
                              ?,
                              ?,
                              ?,
                              ?,
                              ?, 
                              ?, 
                              ?,
                              ?,
                              ?,        
                              sysdate
                              )
                                ''';





           int insertNum= jt.update(InsertSql,OBJECTIVE_GUID,callid,callType,agentCode,agentName,caller,called,accessNumber,alertingTime,pickTime,callInTime,callEndTime,queueDuration,
                   alertingDuration,agentDuration,recordFile,province,city,ivrInputInfo,status);


            log.debug("插入TDX_EVENT_LIST表返回行数："+insertNum);
          }else{
              log.debug("收到【泰迪熊】话单表修改数据："+callid);
              String UpdateSql='''   
                              Update
                              TDX_BILL_LIST
                               SET 
                              OBJECTIVE_GUID=?,
                              callType=?,
                              agentCode=?,
                              agentName=?,
                              caller=?,
                              called=?,
                              accessNumber=?,
                              alertingTime=?,
                              pickTime=?,
                              callInTime=?,
                              callEndTime=?,
                              queueDuration=?,
                              alertingDuration=?,
                              agentDuration=?,
                              recordFile=?,
                              province=?,
                              city=?,
                              ivrInputInfo=?,
                              STATUS=?,
                              UPDATEDATE=sysdate
                              WHERE callid=?
                                ''';
              int updateNum= jt.update(UpdateSql,OBJECTIVE_GUID,callType,agentCode,agentName,caller,called,accessNumber,alertingTime,pickTime,callInTime,callEndTime,queueDuration,
                      alertingDuration,agentDuration,recordFile,province,city,ivrInputInfo,status,callid);
              log.debug("修改TDX_EVENT_LIST表返回行数："+updateNum);

          }

            long endtime=System.currentTimeMillis();
            result.put("result", 200);
            result.put("message","处理成功！耗时:"+(endtime-starttime)+"毫秒");
            result.put("timestamp",timestamp);


        }catch (Exception e) {
            log.error("接口处理异常", e);
            result.put("result", -1);
            result.put("message","接口处理异常:"+ e.getMessage());

        }


        return result.toString();
    }

    // MD5加码。32位
    public static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];

        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }


    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

}
